package com.gitee.wsl.doc.prosemirror.plugin

import com.gitee.wsl.doc.prosemirror.state.EditorState


/**
 * A key is used to [tag](#state.PluginSpec.key) plugins in a way
 * that makes it possible to find them, given an editor state.
 * Assigning a key does mean only one plugin of that type can be
 * active in a state.
 */
class PluginKey<PluginState>(name: String = "key") {

    internal val key: String = createKey(name)

    /**
     * Get the active plugin with this key, if any, from an editor state.
     */
    fun get(state: EditorState): Plugin<PluginState>? {
        return state.config.pluginsByKey[this.key] as Plugin<PluginState>?
    }

    /**
     * Get the plugin's state from an editor state.
     */
    fun getState(state: EditorState): PluginState? {
        return state.stateFields[key] as PluginState?
    }

    companion object{

        val keys = mutableMapOf<String, Int>()

        fun createKey(name: String): String {
            val value = keys[name]
            return if (value == null) {
                keys[name] = 0
                "$name$"
            } else {
                val newValue = value + 1
                keys[name] = newValue
                "$name$$newValue"
            }
        }
    }
}

